﻿using System;
using System.Text;

namespace Sencha.Serialization
{
	public sealed class JsonStringBuilderWriter : JsonWriterBase
	{
		StringBuilder m_jsString;

		public StringBuilder Builder { get { return m_jsString; } }

		public JsonStringBuilderWriter(StringBuilder builder)
			: this(builder, new AdHocSerializer())
		{

		}
		public JsonStringBuilderWriter(StringBuilder builder, ISerializationContext context)
			: base(context)
		{
			if (builder == null)
				throw new ArgumentNullException("builder");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_jsString = builder;
		}


		public override void Flush()
		{
		}

		public override void WriteJson(string jsonString)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_jsString.Append(jsonString);
			this.CharactersWritten += jsonString.Length;
		}
		public override void WriteJson(char[] jsonString, int offset, int charactersToWrite)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			if (offset < 0 || offset >= jsonString.Length)
				throw new ArgumentOutOfRangeException("offset");
			if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length)
				throw new ArgumentOutOfRangeException("charactersToWrite");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			if (charactersToWrite == 0)
				return;

			m_jsString.Append(jsonString, offset, charactersToWrite);
			this.CharactersWritten += charactersToWrite;
		}

		public override string ToString()
		{
			return m_jsString.ToString();
		}
	}
}
